﻿using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace MetaMapics.Gpx
{
  [XmlRoot("gpx")]
  public class Gpx
  {
    [XmlAttribute("version")]
    public string Version { get { return "1.1"; } set { } }
    [XmlAttribute("creator")] public string Creator { get; set; }
    [XmlElement("metadata")] public Metadata Metadata { get; set; }
    [XmlElement("wpt")] public List<Waypoint> Waypoints { get; set; }
    [XmlElement("rte")] public List<Route> Routes { get; set; }
    [XmlElement("trk")] public List<Track> Tracks { get; set; }
    [XmlElement("extensions")] public Extensions Extensions { get; set; }

    public Gpx()
    {
    }

    public Gpx(string creator)
    {
      Creator = creator;
      Waypoints = new List<Waypoint>();
      Routes = new List<Route>();
      Tracks = new List<Track>();
    }

    public void Save(string filePath)
    {
      XmlSerializer serializer = new XmlSerializer(typeof(Gpx), "http://www.topografix.com/GPX/1/1");
      using (Stream stream = File.Create(filePath))
        serializer.Serialize(stream, this);
    }

    public static Gpx Load(string filePath)
    {
      Gpx gpx = null;
      var settings = new XmlReaderSettings();
      settings.IgnoreComments = true;
      settings.IgnoreProcessingInstructions = true;
      settings.IgnoreWhitespace = true;
      using (var reader = XmlReader.Create(filePath, settings))
      {
        if (reader.IsStartElement("gpx"))
        {
          string defaultNamespace = reader["xmlns"];
          XmlSerializer serializer = new XmlSerializer(typeof(Gpx), defaultNamespace);
          gpx = (Gpx)serializer.Deserialize(reader);
        }
      }
      return gpx;
    }
  }
}
